import { isMobile } from "./utils"
import { ElMessage, ElNotification } from "element-plus"
import XLSX from "xlsx";
import FileSaver from "file-saver";
import JSZip from "jszip";
import { ApiDownloadImage } from "../http/api";
import store from '../store'


const GenFileName = (prefix = '发票信息') => {
    //保存文件名添加日期后缀
    let date = new Date();
    let year = date.getFullYear();
    let month = (date.getMonth() + 1).toString().padStart(2, "0");
    let day = date.getDate().toString().padStart(2, "0");
    //文件名
    let fileSaveName = `${prefix}-${year}.${month}.${day}.xlsx`;
    return fileSaveName
}

//下载数据
const DownloadAsExcelFile = (eleId) => {
    if (isMobile()) {
        ElMessage.warning("请在电脑端使用!");
        return;
    }
    let fileSaveName = GenFileName();
    //创建Excel对象
    let fixNode = document.querySelector(".el-table__fixed");
    let tabNode = document.querySelector(`#${eleId}`);
    let wb;
    if (fixNode) {
        wb = XLSX.utils.table_to_book(tabNode.removeChild(fixNode), {
            raw: true,
        });
        tabNode.appendChild(fixNode);
    } else {
        wb = XLSX.utils.table_to_book(tabNode, { raw: true });
    }
    const ws = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
    });
    try {
        FileSaver.saveAs(
            new Blob([ws], { type: "application/octet-stream" }),
            fileSaveName
        );
    } catch (e) {
        ElMessage.error(e);
    }
};


//数组数据导出
const DownloadInvDetail = (callback) => {
    callback(true)
    let invList = store.state.invList
    if (invList.length < 1) {
        ElNotification.warning("没有发票数据可导出!!!")
        return
    }
    //表头
    let header = []
    for (let idx in invList) {
        header = Array.from(new Set([...header, ...Object.keys(invList[idx])]))
    }
    //移除多余项
    let extra = ['url', 'invTip', 'invCode', 'invNum', 'invDate', 'invMoney', 'invChk', 'status', 'code', 'loading']
    for (let i in extra) {
        let idx = header.indexOf(extra[i])
        if (idx !== -1) header.splice(idx, 1)
    }
    //数据
    let data = [header];
    for (let idx in invList) {
        let row = [];
        for (let rowIdx in header) {
            let key = header[rowIdx]
            let val = invList[idx][key]
            if (key === '发票代码') val = val || invList[idx]['invCode']
            if (key === '发票号码') val = val || invList[idx]['invNum']
            if (key === '开票日期') val = val || invList[idx]['invDate']
            if (key === '校验码') val = val || invList[idx]['invChk']
            if (key === '开具金额') val = val || invList[idx]['invMoney']
            row.push(val)
        }
        data.push(row)
    }
    let filename = GenFileName("发票详情")
    let ws_name = "Sheet1"; //Excel第一个sheet的名称
    let wb = XLSX.utils.book_new();
    let ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, ws_name);  //将数据添加到工作薄
    XLSX.writeFile(wb, filename); //导出Excel
    callback(false)
}

// 批量下载图片
const DownloadImageBatch = async (callback) => {
    callback(true)
    let urlList = store.state.invList.map((item) => {
        let filename = item.fileName
            .replace(".pdf", ".png")
            .replace(".PDF", ".png")
            .replace(".bmp", ".png")
            .replace(".jpg", ".png")
            .replace(".jpeg", ".png");
        let url = item.url;
        return { filename, url };
    });

    const zip = new JSZip();
    const cache = {};
    const promises = [];
    await urlList.forEach((item) => {
        if (item.url) {
            const promise = ApiDownloadImage(item.url, {
                responseType: "arraybuffer",
            }).then((data) => {
                zip.file(item.filename, data, {
                    binary: true,
                });
                cache[item.filename] = data.toString();
            });
            promises.push(promise);
        }
    });
    Promise.all(promises).then(() => {
        zip
            .generateAsync({
                type: "blob",
            })
            .then((content) => {
                callback(false)
                FileSaver.saveAs(content, "查验截图.zip");
            });
    });
};

export {
    DownloadAsExcelFile, DownloadImageBatch, DownloadInvDetail
}